/**
 *
 */
package com.legrand.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.legrand.core.exception.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
*@author xiah
*2018-07-12 01:33:41
*/
@Component
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {

       @Autowired
       ObjectMapper mapper;

       @Override
       public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                           AuthenticationException exception) throws IOException, ServletException {
              response.setStatus(HttpStatus.UNAUTHORIZED.value());
              response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
              Response resp = null;
              if ( exception instanceof BadCredentialsException ) {
                     resp = Response.COMMON_UNAUTHORIZED_EXCEPTION;
              }
              PrintWriter writer = response.getWriter();
              mapper.writeValue(writer, resp);
              writer.flush();
              writer.close();
       }

}
